package com.youfang.sixthmedia.controller;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.commons.io.FileUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ListView;
import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.client.HttpClient;
import ch.boye.httpclientandroidlib.client.methods.HttpGet;
import ch.boye.httpclientandroidlib.util.EntityUtils;

import com.gzit.utils.StringUtils;
import com.youfang.sixthmedia.common.BuildingAdapter;
import com.youfang.sixthmedia.common.YoufangContext;
import com.youfang.sixthmedia.message.model.Building;
import com.youfang.sixthmedia.net.HttpRemoter;

public class LogoController extends Thread {

	private static final String TAG = "LogoController";

	
	private BlockingQueue<Building> downloadQueue = new LinkedBlockingQueue<Building>();

	private ListView listview;
	private BuildingAdapter adapter;

	private boolean running = true;

	// ///////////Cache部分//////////////
	public static class Cache {
		private static String logoCachePath = YoufangContext.APP_DIR + "logo"
				+ File.separator;


		static {
			ensureCachePath();
		}

		private static void ensureCachePath() {
			File file = new File(logoCachePath);
			if (!file.exists()) {
				file.mkdirs();
			}
		}

		public static void clearCache() throws IOException {
			FileUtils.cleanDirectory(new File(logoCachePath));
		}

		public static Bitmap getFromCache(Building b) throws Exception {
			String logo = logoCachePath + b.innerID;
			File logoFile = new File(logo);
			if (!logoFile.exists()) {
				return null;
			}
			return BitmapFactory.decodeFile(logo);

		}

		private static void cache(Building b,byte[] resultBytes)throws Exception {
			// 将logo数据保存到缓存目录下
			 File logoFile = new File(logoCachePath + b.innerID);
			 FileUtils.writeByteArrayToFile(logoFile,resultBytes);
		}

		// /////////////////////////////////////////////////
	}

	public LogoController() {
		this.setName("LogoController");
		this.start();

	}

	public void setup(ListView listview, BuildingAdapter adapter) {
		this.listview = listview;
		this.adapter = adapter;
	}

	// 通知图标已就绪
	public void notifyLogoReady(Building b) {

		final int begin = this.listview.getFirstVisiblePosition();
		int end = this.listview.getLastVisiblePosition();

		for (int i = begin; i <= end; i++) {
			if (b.innerID == this.listview.getItemIdAtPosition(i)) {

				this.listview.post(new Runnable() {

					@Override
					public void run() {
						adapter.notifyDataSetChanged();
						listview.setSelection(begin);

					}
				});

			}

		}

	}

	public void onMore(List<? extends Building> builds) {
		for (Building b : builds) {

			// LOGO已经存在或者logo的地址不存在，则不放入下载队列
			if (b.logoBitmap != null || StringUtils.isStickBlank(b.logo)) {
				continue;
			}

			// 没取到则放入下载队列
			downloadQueue.offer(b);
		}

	}

	private void doDownload(Building b) {

		HttpClient client = HttpRemoter.getYoufangRemoter().getHttpClient();
		try {

			URI logoURI = new URI(b.logo);
			HttpGet get = new HttpGet(logoURI);
			HttpResponse resp = client.execute(get);
			int statusCode = resp.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				Log.d(TAG, "logo download failed!statuscode:" + statusCode
						+ ":" + b.logo);
				return;
			}

			byte[] resultBytes = EntityUtils.toByteArray(resp.getEntity());
			Bitmap bitmap = BitmapFactory.decodeByteArray(resultBytes, 0,
					resultBytes.length);
			b.logoBitmap = bitmap;

			// 缓存图标
			Cache.cache(b,resultBytes);

			// 通知logo已下载
			notifyLogoReady(b);

			Log.d(TAG, "logo download ok:" + b.logo);

		} catch (Exception e) {
			e.printStackTrace();
			Log.d(TAG,
					"logo download failed:" + b.logo + "message:"
							+ e.getMessage());

			return;

		}

	}

	public void run() {
		while (running) {
			Building b;
			try {
				b = downloadQueue.take();
				doDownload(b);
				if (this.isInterrupted()) {
					return;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
				running = false;
			}

		}

		Log.i(TAG, "LogoController Thread stopped!");

	}

	// 在刷新时候调用
	public void onRefresh(List<Building> buildings) {

		Log.i(TAG, "LogoController onRefresh!");
		this.downloadQueue.clear();
		this.onMore(buildings);
	}

	// 在activity停止的时候调用该方法停止logo的处理
	public void onStop() {

		Log.i(TAG, "LogoController OnStop!");

		this.running = false;
		this.interrupt();
		this.downloadQueue.clear();

	}

	public void onDestroy() {
		Log.i(TAG, "LogoController onDestroy!");

	}

}
